package com.liziba.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @auther LiZiBa
 * @date 2020/10/19 22:37
 * @description:
 **/
public class ProcessHandlerThread implements Runnable{

    private Object service;
    private Socket socket;

    public ProcessHandlerThread(Object service, Socket socket) {
        this.service = service;
        this.socket = socket;
    }

    @Override
    public void run() {

        try(
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ) {
            // 输入流中获取数据，反序列化
            RpcRequest rpcRequest = (RpcRequest)inputStream.readObject();
            Object o = invoke(rpcRequest);
            outputStream.writeObject(o);
            outputStream.flush();
        }catch (Exception e) {
            //TODO
        }
    }

    private Object invoke(RpcRequest rpcRequest) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Class clazz = Class.forName(rpcRequest.getClazzName());
        Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getTypes());

        return method.invoke(service,rpcRequest.getParams());
    }
}
